package com.heima.datasync.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.search.ArticleIndexConstants;
import com.heima.common.exception.CustomException;
import com.heima.datasync.mapper.ApArticleMapper;
import com.heima.datasync.service.EsDataService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vo.SearchArticleVo;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class EsDataServiceImpl implements EsDataService {
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public ResponseResult dataInit() {
        //查询全部文章
        List<ApArticle> allArticles = apArticleMapper.findAllArticles();
        //判断文章是否为空
        if (allArticles == null || allArticles.size() == 0) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        // 遍历页码批量插入到索引库
        BulkRequest bulkRequest = new BulkRequest(ArticleIndexConstants.ARTICLE_INDEX_NAME);
        //遍历文章集合
        for (ApArticle allArticle : allArticles) {
            //创建SearchArticleVo封装对象
            SearchArticleVo searchArticleVo = new SearchArticleVo();
            //拷贝文章到searchArticleVo对象中
            BeanUtils.copyProperties(allArticle, searchArticleVo);
            //将searchArticleVo转化为JSON字符串
            String ArticleVoStr = JSON.toJSONString(searchArticleVo);
            //设置文档id
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.id(allArticle.getId().toString());
            indexRequest.source(ArticleVoStr,XContentType.JSON);
            // 添加到批量插入对象
            bulkRequest.add(indexRequest);
        }
        try {
            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            return ResponseResult.okResult(bulk.status());
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"批量插入文章失败");
        }
    }
}
